import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ivy_baby_record/user/api/login/register_fast.dart';
import 'package:ivy_baby_record/user/constants/constants.dart';
import 'package:ivy_baby_record/user/constants/route_page.dart';
import 'package:ivy_baby_record/user/db/database_util.dart';
import 'package:ivy_baby_record/user/api/verify/verify.impl.dart';
import 'package:ivy_baby_record/user/db/user_database_util.dart';
import 'package:ivy_baby_record/user/global/global_info.dart';
import 'package:ivy_baby_record/user/model/app_settings.dart';
import 'package:ivy_baby_record/user/model/child.dart';
import 'package:ivy_baby_record/user/util/user_util.dart';
import 'package:ivy_baby_record/user/util/util.dart';
import 'package:ivybaby_api/api/base/api_base.dart';
import 'package:ivybaby_api/api/config/global_data.dart';

class LoginUtil {
  static void checkIsNeedInitChild(BuildContext context) async {
    await Future(() async {
      return DatabaseUtil.inst.database.settingDao.findProfile();
    }).then((value) {
      if (value == null) {
        /// 无登录信息，默认以游客身份登录
        ApiUtils.inst.specialUnionLogin().then((value) {
          if (value.isSuccess && value.data != null) {
            /// 游客登录成功
            Profile profile = Profile(json.encode(value.data), 72000);
            DatabaseUtil.inst.database.settingDao.insertProfile(profile);

            RegisterRspData data = value.data!;
            updateAppDeviceInfoByLastLoginData(data);

            if ((data.memberChilds??[]).isEmpty && (data.accountChilds??[]).isEmpty) {
              /// 游客没有宝宝，需要跳转到初始化添加宝宝页面
              if (data.account != null) {
                /// 保存游客相关信息
                Future(() async {
                  await UserDatabaseUtil.inst.init(Constants.GUEST_MEM_ID);
                  UserDatabaseUtil.inst.database.accountDao.insertAccount(data.account!)
                      .then((value) {
                    print('insert account id : ${data.account?.id}');
                  });
                });
              }
              Navigator.of(context).popAndPushNamed(RoutePage.PAGE_INIT);
              return;
            } else {
              /// 游客有宝宝，保存相关信息
              Future(() async {
                await UserDatabaseUtil.inst.init(Constants.GUEST_MEM_ID);
                UserDatabaseUtil.inst.database.accountDao.insertAccount(data.account!)
                    .then((value) {
                  print('insert account id : ${data.account?.id}');
                });
                UserDatabaseUtil.inst.database.childDao.insertChildren(data.accountChilds!)
                    .then((value) {
                  print('insert child id : ${data.accountChilds?[0].id}');
                });
                checkNavigationToHome(context);
              });
            }
          }
        });
      } else {
        /// 之前有登录信息，使用之前的信息
        Future(() async {
          if ((value.lastLoginInfo ?? '').isNotEmpty) {
            RegisterRspData loginData = RegisterRspData.fromJson(json.decode(value.lastLoginInfo));
            await UserDatabaseUtil.inst.init(loginData.member == null ? Constants.GUEST_MEM_ID : loginData.member!.id);
            if ((loginData.accountChilds??[]).isEmpty && (loginData.memberChilds??[]).isEmpty) {
              /// 有登录信息但是没有宝宝，需要初始化宝宝信息
              Navigator.of(context).popAndPushNamed(RoutePage.PAGE_INIT);
              return;
            }
            updateAppDeviceInfoByLastLoginData(loginData);
          }
          checkNavigationToHome(context);
        });
      }
    });
  }

  static void checkNavigationToHome(BuildContext context) {
    print('checkNavigationToHome ${GlobalInfo.inst.childId}');
    if (UserUtils.isGuest()) {
      Navigator.popAndPushNamed(context, RoutePage.PAGE_REG_LOGIN);
    } else {
      Navigator.of(context).popAndPushNamed(RoutePage.PAGE_RECORD_HOME);
    }
  }

  static void updateToken(String token) {
    GlobalData.appDevice.token = token;
  }

  static void updateAccountId(String id) {
    GlobalData.appDevice.accountId = id;
  }

  static void updateAppDeviceInfoByLastLoginData(RegisterRspData? loginData) {
    if (loginData != null) {
      GlobalData.appDevice.userId = Util.parseInt(loginData.member == null ? Constants.GUEST_MEM_ID : loginData.member!.id);
      GlobalData.appDevice.token = loginData.userToken!;
      GlobalData.appDevice.accountId = loginData.account!.id;
      Child? child;
      if (loginData.memberChilds != null && loginData.memberChilds!.length > 0) {
        Util.sortChild(loginData.memberChilds, false);
        child = loginData.memberChilds![0];
        GlobalInfo.inst.child = child;
      } else if (loginData.accountChilds != null && loginData.accountChilds!.length > 0) {
        Util.sortChild(loginData.accountChilds, false);
        child = loginData.accountChilds![0];
        GlobalInfo.inst.child = child;
      }
      if (child != null) {
        GlobalData.appDevice.expectedDate = child.expectedDate.toString();
        GlobalData.appDevice.birthday = child.birthday.toString();
        GlobalData.appDevice.gestation = child.gestationStatus;
        GlobalData.appDevice.premature = child.prematureDelivery;
        GlobalData.appDevice.loginType = loginData.account!.type.toString();
      }
    }
  }

  static void loginResultProcess(BuildContext context, RegisterRsp value) {
    if (value.isSuccess) {
      if (value.data?.member != null) {
        updateAppDeviceInfoByLastLoginData(value.data!);
        Navigator.of(context).pop();
        Navigator.of(context).popAndPushNamed(RoutePage.PAGE_RECORD_HOME);
        Future(() async {
          await UserDatabaseUtil.inst.init(value.data!.member!.id);
          UserDatabaseUtil.inst.database.accountDao.insertAccount(value.data!.account!);
          UserDatabaseUtil.inst.database.memberDao.insertMember(value.data!.member!);
          UserDatabaseUtil.inst.database.childDao.insertChildren(value.data!.memberChilds!);
          DatabaseUtil.inst.database.settingDao.findProfile().then((profile) {
            profile!.lastLoginInfo = json.encode(value.data);
            DatabaseUtil.inst.database.settingDao.updateProfile(profile);
          });
        });
      }
    }
  }
}